import {
  getInfo,
  getUserList,
  updateUser,
  deleteUser,
  updatePass,
  updateEmail,
  updateAvatar,
  sendEmail,
} from "@/api/user"; // 引入请求

// 封装了一个默认的state数据
const getDefaultState = () => {
  return {
    user: {} // 用户信息
  };
};

// 赋值默认state
const state = getDefaultState();

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState()); // 用于清空重置state
  },
  SET_USER_INFO: (state, user) => {
    state.user = user; // 保存所有用户信息
  }
};

const actions = {
  // 用户列表
  getUserList({ commit }, data) {
    return new Promise((resolve, reject) => {
      getUserList(data)
        .then(response => {
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // 当前用户信息请求
  getInfo({ commit }, data) {
    return new Promise((resolve, reject) => {
      getInfo(data)
        .then(response => {
          commit("SET_USER_INFO", response.data.userInfo); // 保存用户信息
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // 更新用户信息
  updateUser({ commit }, data) {
    return new Promise((resolve, reject) => {
      updateUser(data)
        .then(response => {
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // 删除用户
  deleteUser({ commit }, data) {
    return new Promise((resolve, reject) => {
      deleteUser(data)
        .then(response => {
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // 修改用户密码
  updatePass({ commit }, data) {
    return new Promise((resolve, reject) => {
      updatePass(data)
        .then(response => {
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // 修改邮箱
  updateEmail({ commit }, data) {
    return new Promise((resolve, reject) => {
      updateEmail(data)
        .then(response => {
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // 上传头像
  updateAvatar({ commit }, data) {
    return new Promise((resolve, reject) => {
      updateAvatar(data)
        .then(response => {
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // 发送验证码
  sendEmail({ commit }, data) {
    return new Promise((resolve, reject) => {
      sendEmail(data)
        .then(response => {
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  },
};

export default {
  namespaced: true, // 命名空间
  state,
  mutations,
  actions
};
